package org.luo.lan.common.handler;

import lombok.extern.slf4j.Slf4j;

import java.io.Serializable;
import java.io.UnsupportedEncodingException;

/**
 * @Auther: luobiao
 * @Date: 2020/9/25 06:44
 * @Description:
 */
@Slf4j
public class Request implements Serializable {
    private byte type;
    private byte[] header;
    private byte[] body;
    private byte status;

    private Request(byte type, byte[] body, byte status) {
        this.type = type;
        this.body = body;
        this.status = status;
    }

    private Request(byte type, String body, byte status) {
        this.type = type;
        this.body = body.getBytes();
        this.status = status;
    }

    public static Request SUCCESS(byte type,byte[] body){
        return new Request(type,body,(byte) 1);
    }

    public static Request SUCCESS(byte type,String body){
        return new Request(type,body.getBytes(),(byte) 1);
    }

    public static Request FAIL(byte type,byte[] body){
        return new Request(type,body,(byte) 0);
    }

    public static Request FAIL(byte type,String body){
        return new Request(type,body.getBytes(),(byte) 0);
    }

    public boolean isSuccess(){
        return this.status == 1;
    }

    public byte getType() {
        return type;
    }

    public byte[] getBody() {
        return body;
    }

    public byte getStatus() {
        return status;
    }

    public void setStatus(byte status) {
        this.status = status;
    }

    public String getStringBody(){
        try {
            return new String(body,"utf-8");
        } catch (UnsupportedEncodingException e) {
            log.error("getStringBody失败！body={}",body);
            return "";
        }
    }

    public byte[] getHeader() {
        return header;
    }

    public String getStringHeader(){
        try {
            return new String(header,"utf-8");
        } catch (UnsupportedEncodingException e) {
            log.error("getStringBody失败！header={}",header);
            return "";
        }
    }

    public Request addHeader(byte[] header) {
        this.header = header;
        return this;
    }

    public Request addHeader(String header){
        this.header = header.getBytes();
        return this;
    }
}
